﻿using AutoMapper;
using Lazy.Captcha.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartConference.Api.DTO;
using SmartConference.Api.Filter;
using SmartConference.Domain;
using SmartConference.ErrorCode;
using SmartConference.Infrastructure.Interfaces;
using System.Threading.Tasks;

namespace SmartConference.Api.Controllers
{
    /// <summary>
    /// 验证码
    /// </summary>
    [Route("captcha")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "用户管理")]
    public class CaptchaController : Controller
    {
        private readonly ICaptcha _captcha;
        private readonly IBaseRepository<UserInfo> baseRepository;
        private readonly IMapper mapper;
        private readonly JWTHelper jwtHelper;

        public CaptchaController(ICaptcha captcha,IBaseRepository<UserInfo> baseRepository,IMapper mapper, JWTHelper jwtHelper)
        {
            _captcha = captcha;
            this.baseRepository = baseRepository;
            this.mapper = mapper;
            this.jwtHelper = jwtHelper;
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="id">手机号</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Captcha(string id)
        {
            var info = _captcha.Generate(id);
            // 有多处验证码且过期时间不一样，可传第二个参数覆盖默认配置。
            //var info = _captcha.Generate(id,120);
            var stream = new MemoryStream(info.Bytes);
            return File(stream, "image/gif");
        }

        /// <summary>
        /// 演示时使用HttpGet传参方便，这里仅做返回处理
        /// </summary>
        [HttpGet("validate")]
        public async Task<ApiResult<UserLoginDTO>> Validate(string phone, string code)
        {
            bool IsSuc= _captcha.Validate(phone, code);
            if (IsSuc == true)
            {
                var userinfo = await baseRepository.GetAsync(x => x.PhoneNumber == phone);
                var newinfo=mapper.Map<UserLoginDTO>(userinfo);
                newinfo.Jwt= jwtHelper.CreateToken(newinfo.IDNumber, newinfo.UserNumber);
                return ApiResult<UserLoginDTO>.Success(ApiResultCode.Success, newinfo); 
            }
            return ApiResult<UserLoginDTO>.Error(ApiResultCode.Error, "验证码错误");
        }

        /// <summary>
        /// 多次校验（https://gitee.com/pojianbing/lazy-captcha/issues/I4XHGM）
        /// 演示时使用HttpGet传参方便，这里仅做返回处理
        /// </summary>
        [HttpGet("validate2")]
        public bool Validate2(string id, string code)
        {
            return _captcha.Validate(id, code, false);
        }
    }
}
